/*
 * @Description: 添加导航弹窗
 * @Author: Rfan
 * @Date: 2022-04-21 15:52:13
 * @LastEditTime: 2022-05-25 08:48:05
 */

import { useCallback, useEffect } from 'react';
import { Button, Form, Modal } from 'antd';
import InfoForm from './common/InfoForm';
import { useFuncAndNavContext } from '../../contexts/FuncAndNavContext';
import type { ICommonDialog } from '@/interfaces/global';

interface IEditNavDialogProps extends ICommonDialog {
  data: any;
}

const EditNavDialog = (props: IEditNavDialogProps) => {
  const { visible, data, onClose } = props;
  const { editNavItem } = useFuncAndNavContext();
  const [form] = Form.useForm();

  // 缓存关闭方法
  const memoizedClose = useCallback(() => onClose(), []);

  useEffect(() => {
    if (visible) {
      data.navLevel = data.pid ? 2 : 1;
      form.setFieldsValue(data);
    }
  }, [visible]);

  const onCancel = () => {
    memoizedClose();
  };

  /**
   * @description: 点击确认按钮触发表格提交
   */
  const confirm = () => {
    form.submit();
  };

  /**
   * @description: 保存导航
   * @param {any} vals
   */
  const saveNav = (vals: any) => {
    editNavItem(vals).then(() => {
      memoizedClose();
    });
  };

  const onFinish = (values: any) => {
    if (values.navLevel === 1) {
      values.pid = 0;
    } else {
      values.pid = values.pid || 0;
    }
    delete values.navLevel;
    saveNav({ ...data, ...values });
  };

  return (
    <Modal
      title="编辑权限"
      visible={visible}
      width={600}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={confirm}>
          确定
        </Button>
      ]}
    >
      <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} onFinish={onFinish}>
        <InfoForm />
      </Form>
    </Modal>
  );
};

export default EditNavDialog;
